package com.zt.bus.alipay.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.zt.bus.alipay.util.AlipayUtil;
import com.zt.bus.constant.BusConstant;
import com.zt.bus.order.model.OrderPayment;
import com.zt.bus.order.service.OrderBackService;
import com.zt.bus.order.service.OrderPaymentService;
import com.zt.bus.wx.util.PayUtil;
import com.zt.system.model.BusinessException;
import com.zt.system.service.BaseService;
import com.zt.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/6/30.
 */

@Service
public class AliPayService extends BaseService {

    private static final Logger LOG = Logger.getLogger(AliPayService.class);

    @Autowired
    private OrderPaymentService orderPaymentService;

    @Autowired
    private OrderBackService orderBackService;

    public OrderPayment orderPayRefund(String tradeNo, String payPlatformNo, String orderFee, String refundFee) {

        LOG.info("支付宝退款开始");

        if (StringUtil.isEmpty(tradeNo) || StringUtil.isEmpty(payPlatformNo)) {
            throw new BusinessException("交易订单号不存在!");
        }
        if (StringUtil.isEmpty(orderFee) || StringUtil.isEmpty(refundFee)) {
            throw new BusinessException("退订的金额为空!");
        }

        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest(); // 统一收单交易退款接口
        // 只需要传入业务参数
        Map<String, Object> param = new HashMap<>();
        param.put("trade_no", payPlatformNo);// 支付宝订单号
        param.put("refund_amount", 0.01);// 退款金额
        param.put("refund_reason", "支付宝退款测试");// 退款金额
        param.put("out_request_no", PayUtil.getRefundNo()); // 退款单号
        alipayRequest.setBizContent(JSONObject.fromObject(param).toString()); // 不需要对json字符串转义

        Map<String, Object> restmap = new HashMap<>();// 返回支付宝退款信息
        OrderPayment orderPayment = null;
        try {
            AlipayTradeRefundResponse alipayResponse = AlipayUtil.getAlipayClient().execute(alipayRequest);
            if (alipayResponse.isSuccess()) {
                // 调用成功，则处理业务逻辑
                if ("10000".equals(alipayResponse.getCode())) {
                    // 退款成功
                    restmap.put("out_trade_no", alipayResponse.getOutTradeNo());
                    restmap.put("trade_no", alipayResponse.getTradeNo());
                    restmap.put("buyer_logon_id", alipayResponse.getBuyerLogonId());// 用户的登录id
                    restmap.put("gmt_refund_pay", alipayResponse.getGmtRefundPay()); // 退看支付时间
                    restmap.put("buyer_user_id", alipayResponse.getBuyerUserId());// 买家在支付宝的用户id
                    // 退款成功修改退款状态，更新退款流水号
                    orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
                    orderPayment.setPayPlatformNo((String) restmap.get("trade_no"));
                    orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_SUCCESS);
                    orderPayment.setPayTime(new Date());
                    orderPayment.setResultMsg(tradeNo + "退款成功,支付宝退款单号:" + restmap.get("trade_no"));
                    orderPaymentService.updateOrderPayment(orderPayment);
                    orderBackService.updateOrderBackStatus(orderPayment.getOrderId(),
                            BusConstant.OrderBackStatus.REFUND_SUCCESS);
                    LOG.info("订单号：" + tradeNo + "退款成功");
                    LOG.info(JSONObject.fromObject(restmap));
                } else {
                    //退款失败修改退款状态，更新退款流水号
                    orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
                    orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_FAIL);
                    orderPayment.setPayTime(new Date());
                    orderPayment.setResultMsg(tradeNo + "订单退款失败:" + alipayResponse.getCode() + ":" + alipayResponse.getSubMsg());
                    orderPaymentService.updateOrderPayment(orderPayment);
                    orderBackService.updateOrderBackStatus(orderPayment.getOrderId(), BusConstant.OrderBackStatus.REFUND_FAIL);
                    LOG.info("订单号：" + tradeNo + "退款失败:" + alipayResponse.getMsg() + ":" + alipayResponse.getSubMsg());
                }
            }
        } catch (AlipayApiException e) {
            //退款失败修改退款状态，更新退款流水号
            orderPayment = orderPaymentService.getByPrimaryKey(tradeNo);
            orderPayment.setPayStatus(BusConstant.OrderBackStatus.REFUND_FAIL);
            orderPayment.setPayTime(new Date());
            orderPayment.setResultMsg(tradeNo + "订单退款失败: 请求支付宝退款方法异常!");
            orderPaymentService.updateOrderPayment(orderPayment);
            orderBackService.updateOrderBackStatus(orderPayment.getOrderId(), BusConstant.OrderBackStatus.REFUND_FAIL);
            LOG.info(e.getMessage());
            e.printStackTrace();
        }
        LOG.info("支付宝退款结束");
        return orderPayment;
    }
}
